package com.huixue.cn.ztej.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.util.WebUtils;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.huixue.cn.ztej.bean.Results;
import com.huixue.cn.ztej.bean.Role;
import com.huixue.cn.ztej.bean.Section;
import com.huixue.cn.ztej.bean.TTudentInfo;
import com.huixue.cn.ztej.bean.User;
import com.huixue.cn.ztej.bean.UserPassword;
import com.huixue.cn.ztej.constants.ResourceLocator;
import com.huixue.cn.ztej.constants.UserUtil;
import com.huixue.cn.ztej.enums.RoleStatus;
import com.huixue.cn.ztej.persistence.Domain;
import com.huixue.cn.ztej.service.SysPictureService;
import com.huixue.cn.ztej.service.SysProjectService;
import com.huixue.cn.ztej.service.SysRoleService;
import com.huixue.cn.ztej.service.SysSectionService;
import com.huixue.cn.ztej.service.SysUserService;
import com.huixue.cn.ztej.utils.ImportExcel;
import com.huixue.cn.ztej.utils.MD5;
import com.huixue.cn.ztej.utils.SystemContents.API_RETURN_STATUS;
import com.huixue.cn.ztej.utils.annotation.RequestMappingName;
import com.huixue.cn.ztej.utils.framwork.JacksonUtil;
import com.huixue.cn.ztej.utils.framwork.PageParameter;

@Domain(User.class)
@Controller
@RequestMapping(value = "/sys/user")
public class UserController extends BaseController {

	
	@Autowired(required = true)
	SysUserService sysUserService;
	
	@Autowired(required = true)
	SysRoleService sysRoleService;

	@Autowired(required = true)
	SysProjectService sysProjectService;
	
	@Autowired(required = true)
	SysSectionService sysSectionService;
	
	@RequestMapping(value = "/saveUser")
	public String save(@ModelAttribute("user") User user) {
		user.setCreateTime(new Date());
		sysUserService.saveUser(user);
		return "/register";
	}
	
	@RequestMapping(value = "/listUser")
	public String list(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows", defaultValue = PageParameter.DEFAULT_PAGE_SIZE+"") Integer rows,
			User searchForm,HttpServletRequest request,HttpServletResponse response,Model model) {
		Map<String, Object> searchParams = new HashMap<String,Object>();

		if(StringUtil.isNotEmpty(searchForm.getUserName())){
			searchParams.put("userName", searchForm.getUserName());
		}
		if(StringUtil.isNotEmpty(searchForm.getSex())){
			searchParams.put("sex", searchForm.getSex());
		}
		if(StringUtil.isNotEmpty(searchForm.getEmail())){
			searchParams.put("email", searchForm.getEmail());
		}
		if(StringUtil.isNotEmpty(searchForm.getPhoneNum())){
			searchParams.put("phoneNum", searchForm.getPhoneNum());
		}
		
		//User currentUser = (User)request.getSession().getAttribute("loginUser");
		Results projectRes =  sysProjectService.findAll(searchParams);
		model.addAttribute("projectRes", projectRes);
	
		
		Results results =  sysUserService.searchUserByPage(searchParams,page,rows);	
		
		model.addAttribute("res", results);
		model.addAttribute("searchForm", searchForm);
		
		return "/user/list";
	}
	
	
	@RequestMappingName(value = "跳转到更新页面")
	@RequestMapping(value = "/toUpdate/{userId}")
	public String toUpdate(@PathVariable("userId")Integer userId,Model model,HttpServletRequest request) {
		Map<String, Object> searchParams = new HashMap<String,Object>();
		User currentUser = (User)request.getSession().getAttribute("loginUser");
		if(currentUser.getRoleId()!=null && currentUser.getRoleId().equals(RoleStatus.ROLE_8.getRoleId()+"")){
			searchParams.put("roleIds", new Integer[]{2,3,4,5,6,8});
			searchParams.put("proId", currentUser.getProjectID());
		}
		
		User user = sysUserService.findUserById(Integer.valueOf(userId));
		model.addAttribute("res", user);
		Results roleRs =  sysRoleService.searchRole(searchParams);
		model.addAttribute("roleRs", roleRs);
		
		Results projectRes =   sysProjectService.findAll(searchParams);
		model.addAttribute("projectRes", projectRes);
		
//		List<Section> sectionList = sysSectionService.listSectionByPro(Integer.valueOf(user.getProjectID()));
//		model.addAttribute("sectionRes", sectionList);
		
		//项目查询
		return "/user/user_update";
	}
	
	/*@RequestMappingName(value = "跳转到更新页面")
	@RequestMapping(value = "/update")
	public String update(@ModelAttribute("user") User userForm,Model model,HttpServletRequest request) {
		
		String userId = request.getParameter("user_id");		
		
		User user = sysUserService.findUserById(Integer.valueOf(userId));
		String roleId = request.getParameter("roleId");	
		String status = request.getParameter("status");	
		
		user.setRoleId(userForm.getRoleId());
		user.setStatus(userForm.getStatus());
		user.setLoginName(userForm.getLoginName());
		user.setUserName(userForm.getUserName());
		user.setProjectID(userForm.getProjectID());
		user.setSegmentID(userForm.getSegmentID());
		sysUserService.updateUser(user);
		
		return "redirect:/sys/user/toUpdate/"+user.getUser_id();
	}*/
	
	@RequestMapping(value = "/approve")
	public String approve(HttpServletRequest request,HttpServletResponse response,Model model) {
		String userId = request.getParameter("userId");
		User user = sysUserService.findUserById(Integer.valueOf(userId));
		user.setStatus(UserUtil.APPROVE_YES);
		sysUserService.updateUser(user);
		return "redirect:/sys/user/listUser";
	}
	
	@RequestMapping(value = "/resetPwd/{userId}",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	@ResponseBody
	public Results resetPwd(@PathVariable("userId")Integer userId,
			HttpServletRequest request,HttpServletResponse response,Model model) {
		User user = sysUserService.findUserById(userId);
		user.setPassword(MD5.md5("123456"));
		sysUserService.updateUser(user);
		Results results = new Results(
				API_RETURN_STATUS.NORMAL.value(),
				API_RETURN_STATUS.NORMAL.desc()
				);
		
		return results;
	}
	
	@ResponseBody
	@RequestMapping(value = "/toUpdatePwd",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	public Results toUpdatePwd(@RequestBody UserPassword user,
			HttpServletRequest request,HttpServletResponse response,Model model) {
		User currentUser = (User)request.getSession().getAttribute("loginUser");
		if(!currentUser.getPassword().equals(MD5.md5(user.getOldPassword()))){
			Results results = new Results(
					API_RETURN_STATUS.PASSWORD_ERROR.value(),
					"原密码错误"
					);
			return results;
		}else{
			currentUser.setPassword(MD5.md5(user.getNewPassword()));
			sysUserService.updateUser(currentUser);
			Results results = new Results(
					API_RETURN_STATUS.NORMAL.value(),
					API_RETURN_STATUS.NORMAL.desc()
					);
			return results;
		}
	}
	
	
	@RequestMapping(value = "/updatePwd")
	public String updatePwd(HttpServletRequest request,HttpServletResponse response) {
		return "/user/updatepwd";
	}
	
	@ResponseBody
	@RequestMapping(value = "/disableUser/{userId}/{status}",produces="application/json;charset=UTF-8")
	public Results disableUser(@PathVariable("userId")Integer userId,@PathVariable("status")Integer status,
			HttpServletRequest request,HttpServletResponse response) {
		
		User user = sysUserService.findUserById(userId);
		user.setIsAvailable(status);
		sysUserService.updateUser(user);
		Results results = new Results(
				API_RETURN_STATUS.NORMAL.value(),
				API_RETURN_STATUS.NORMAL.desc()
				);
		
		return results;
	}
	
	/**
	 * 添加角色前
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/toAdd")
	public String toAdd(Model model) {
		return "/user/add";
	}
	
	@ResponseBody
	@RequestMapping(value = "/add",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	public Results add(@RequestBody User user,
			HttpServletRequest request,HttpServletResponse response,Model model){
		user.setPassword(MD5.md5(user.getPassword()));
		user.setRoleId("2");
		user.setIsAvailable(1);
		user.setStatus(2);
		sysUserService.saveUser(user);
		Results results = new Results(API_RETURN_STATUS.NORMAL.value(), "保存成功！");
		return results;
	}
	
	@ResponseBody
	@RequestMapping(value = "/updateUser",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	public Results updateUser(@RequestBody User user,
			HttpServletRequest request,HttpServletResponse response,Model model){
		/*if(StringUtil.isNotEmpty(user.getPassword())){
			user.setPassword(MD5.md5(user.getPassword()));
		}*/
		//user.setIsAvailable(1);
		user.setStatus(2);
		sysUserService.updateUser(user);
		Results results = new Results(API_RETURN_STATUS.NORMAL.value(), "修改成功！");
		return results;
	}
	
	@ResponseBody
	@RequestMapping(value = "delete", produces = "application/json;charset=UTF-8")
	public String examine(HttpServletRequest request,HttpServletResponse response) {
		String userId = request.getParameter("userId");
		User user = new User();
		user.setUser_id(Integer.parseInt(userId));
		user.setStatus(-1);
		sysUserService.deleteforuser(user);
		Map<String, Object> resulMmap = new HashMap<String, Object>();
		resulMmap.put("result", "success");
		return JSON.toJSONString(resulMmap);
	}
	
	@RequestMapping(value = "/toImport")
	public String toImport(Model model) {
		return "/user/user_import";
	}
	
	@RequestMapping(value = "/toupload")
	public String toupload(Model model) {
		return "/upload/uploadImg";
	}
	
	
	@RequestMapping(value = "UploadExcel",produces = "application/json;charset=utf-8")
	@ResponseBody
	public Results UploadExcel(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Results results = new Results();
		String message="";
		try{
			MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
	        MultipartFile excelFile = multipartRequest.getFile("excel");
//			MultipartHttpServletRequest mr = (MultipartHttpServletRequest)request;
			ImportExcel excel = new ImportExcel(excelFile,0,0);
			Row head = excel.getRow(0);
			if(getHeadList(head)){
				Row tempRow = null;
				List<User> items = new ArrayList<User>();
				for (int i = excel.getDataRowNum(); i <= excel.getLastDataRowNum(); i++) {
					User user = new User();
					tempRow = excel.getRow(i);
					Cell curCell = tempRow.getCell(0);
					curCell.setCellType(Cell.CELL_TYPE_STRING);
					if(null!=curCell && !StringUtils.isEmpty(curCell.getStringCellValue())){
						user.setLoginName(curCell.getStringCellValue().trim());
					}else{
						message = "导入数据登录名为空";
						results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), message);
						break;
					}
					Cell curCell1 = tempRow.getCell(1);
					curCell1.setCellType(Cell.CELL_TYPE_STRING);
					if(null!=curCell1 && !StringUtils.isEmpty(curCell1.getStringCellValue())){
						user.setPassword(MD5.md5(curCell1.getStringCellValue().trim()));
					}else{
						message = "导入数据密码为空";
						results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), message);
						break;
					}
					Cell curCell2 = tempRow.getCell(2);
					curCell2.setCellType(Cell.CELL_TYPE_STRING);
					if(null!=curCell2 && !StringUtils.isEmpty(curCell2.getStringCellValue())){
						user.setUserName(curCell2.getStringCellValue().trim());
					}else{
						message = "导入数据姓名为空";
						results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), message);
						break;
					}
					
					Cell curCell3 = tempRow.getCell(3);
					curCell3.setCellType(Cell.CELL_TYPE_STRING);
					if(null!=curCell3 && !StringUtils.isEmpty(curCell3.getStringCellValue())){
						if(curCell3.getStringCellValue().trim().equals("语文")){
							user.setSubjectId(1);
						}else if(curCell3.getStringCellValue().trim().equals("数学")){
							user.setSubjectId(2);
						}else if(curCell3.getStringCellValue().trim().equals("英语")){
							user.setSubjectId(3);
						}
					}else{
						message = "导入数据科目为空";
						results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), message);
						break;
					}
					
					Cell curCell4 = tempRow.getCell(4);
					curCell4.setCellType(Cell.CELL_TYPE_STRING);
					if(null!=curCell4 && !StringUtils.isEmpty(curCell4.getStringCellValue())){
						if(curCell4.getStringCellValue().trim().equals("男")){
							user.setSex("1");
						}else if(curCell4.getStringCellValue().trim().equals("女")){
							user.setSex("2");
						}
					}else{
						message = "导入数据性别为空";
						results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), message);
						break;
					}
					Cell curCell5 = tempRow.getCell(5);
					curCell5.setCellType(Cell.CELL_TYPE_STRING);
					if(null!=curCell5 && !StringUtils.isEmpty(curCell5.getStringCellValue())){
						user.setPhoneNum(curCell5.getStringCellValue().trim());
					}else{
						message = "导入数据手机号为空";
						results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), message);
						break;
					}
					Cell curCell6 = tempRow.getCell(6);
					curCell6.setCellType(Cell.CELL_TYPE_STRING);
					if(null!=curCell6 && !StringUtils.isEmpty(curCell6.getStringCellValue())){
						user.setEmail(curCell6.getStringCellValue().trim());
					}else{
						message = "导入数据性别为空";
						results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), message);
						break;
					}
					user.setRoleId("2");
					user.setIsAvailable(1);
					user.setStatus(2);
					user.setCreateTime(new Date());
					items.add(user);
				}
				
				if(items.size()>0){
					Boolean b = sysUserService.haveUserForList(items);
					if(!b){
						sysUserService.batchInsertUser(items);
						message = "导入成功";
						results = new Results(API_RETURN_STATUS.NORMAL.value(), message);
					}else{
						message = "登录名有重复数据";
						results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), message);
					}
				}
			}else{
				message = "导入数据表头不正确";
				results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), message);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "导入数据发生异常";
			results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), message);
			
		}
		
		return results;
	}
	
	/**
	 * 判断数据表头
	 * @param head
	 * @return
	 */
	private Boolean getHeadList(Row head){
		Boolean b = true;
		if(null==head || head.getLastCellNum()<7){
			b = false;
		}
		for(int j=0; j<head.getLastCellNum();j++){
			Cell curCell = head.getCell(j);
			if(j==0){
				if(null!=curCell && !StringUtils.isEmpty(curCell.getStringCellValue())){
					if(!curCell.getStringCellValue().trim().equals("登录名")){
						b = false;
						break;
					}
				}else{
					b = false;
					break;
				}
			}
			if(j==1){
				if(null!=curCell && !StringUtils.isEmpty(curCell.getStringCellValue())){
					if(!curCell.getStringCellValue().trim().equals("密码")){
						b = false;
						break;
					}
				}else{
					b = false;
					break;
				}
			}
			if(j==2){
				if(null!=curCell && !StringUtils.isEmpty(curCell.getStringCellValue())){
					if(!curCell.getStringCellValue().trim().equals("姓名")){
						b = false;
						break;
					}
				}else{
					b = false;
					break;
				}
			}
			if(j==3){
				if(null!=curCell && !StringUtils.isEmpty(curCell.getStringCellValue())){
					if(!curCell.getStringCellValue().trim().equals("科目")){
						b = false;
						break;
					}
				}else{
					b = false;
					break;
				}
			}
			if(j==4){
				if(null!=curCell && !StringUtils.isEmpty(curCell.getStringCellValue())){
					if(!curCell.getStringCellValue().trim().equals("性别")){
						b = false;
						break;
					}
				}else{
					b = false;
					break;
				}
			}
			if(j==5){
				if(null!=curCell && !StringUtils.isEmpty(curCell.getStringCellValue())){
					if(!curCell.getStringCellValue().trim().equals("电话")){
						b = false;
						break;
					}
				}else{
					b = false;
					break;
				}
			}
			if(j==6){
				if(null!=curCell && !StringUtils.isEmpty(curCell.getStringCellValue())){
					if(!curCell.getStringCellValue().trim().equals("邮箱")){
						b = false;
						break;
					}
				}else{
					b = false;
					break;
				}
			}
		}
		return b;
	}
	

	
}
